<?php

namespace app\api\service;

use app\service\BaseService;
use think\Db;
use think\Exception;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/3/21 0021
 * Time: 11:42
 */
class TraderService extends BaseService
{
    /**
     * @name 出售
     * @author zay
     * @Date 2020/3/21 0021 11:47
     */
    public function sell($appdata, $userinfo)
    {
        Db::startTrans();
        try {
            $num = $appdata['num'];
            $secpwd = $appdata['secpwd'];
            $order_id = $appdata['order_id'];
            //获取可以求购的时间
            $setting = setting();
            if (date('H') < $setting['open_time'] || date('H') >= $setting['open_time_end']) {
                throw new \Exception('开盘时间 '.$setting['open_time'].':00-'.$setting['open_time_end'].':00');
            }
            if (empty($num) || empty($secpwd) || empty($order_id)) {
                throw new \Exception('缺少必要的参数');
            }
            //验证支付密码
            if (md5($secpwd) != $userinfo['secpwd']) {
                throw new \Exception('支付密码不正确');
            }
            //查询订单是否存在
            $order = DB('ppdd')->where(['id' => $order_id, 'is_del' => 0])->whereIn('zt', [0, 1])->find();
            if (empty($order)) {
                throw new \Exception('订单不存在或已完成');
            }
            if ($num <> $order['num']) {
                throw new \Exception('请输入正确的数量');
            }
            //出售扣卖出者手续费
            $sell_fee = setting('sell_fee');
            $sell_fee = round($num * $sell_fee / 100, 2);
            if ($order['p_id'] == $userinfo['id']) {
                throw new \Exception('自己不能购买自己');
            }
            if ($order['num'] - $order['sell_num'] < $num) {
                throw new \Exception('数量不够，无法购买');
            }
            $order_update = ['sell_num' => $order['sell_num'] + $num, 'update_time' => time(), 'zt' => 1];
            $res = DB('ppdd')->where(['id' => $order_id, 'is_del' => 0])->update($order_update);
            if (!$res) {
                throw new Exception('订单更新失败');
            }
            if ($userinfo['idc']-$userinfo['idc_freeze'] < $num + $sell_fee) {
                throw new \Exception('账户币不足');
            }
            //添加交易记录
            $insert_data = [
                'p_order_id' => $order['id'],
                'g_order_sn' => create_sn(),
                'num' => $num,
                'buy_id' => $order['p_id'],
                'buy_user' => $order['p_user'],
                'time' => time(),
                'price' => $order['price'],
                'sell_id' => $userinfo['id'],
                'sell_user' => $userinfo['uname'],
                'total_money' => $order['price'] * $num,
                'zt' => 1,
                'update_time' => time(),
                'type' => 1,
                'fee' => $sell_fee,
            ];
            $jiaoyi_res = DB('ppdd_jiaoyi')->insertGetId($insert_data);
            if (!$jiaoyi_res) {
                throw new \Exception('出售记录添加失败');
            }
            //冻结账户币数量
            $res = DB('user')->where(['id' => $userinfo['id']])->update(['idc_freeze' => $userinfo['idc_freeze'] + $num + $sell_fee, 'update_time' => time()]);
            if (!$res) {
                throw new \Exception('冻结金币失败');
            }
            //记录每次交易单价
            DB('k_hours')->insert(['time' => time(), 'price' => $order['price']]);
            $data = ['jiaoyi_id' => $jiaoyi_res];
            Db::commit();
            //出售成功给对方发短信
            $retsms = sendsms($order['p_user'], 'jypp',2);
            //
            apifasong(['zt' => 1, 'msg' => '出售成功', 'data' => $data]);
        } catch (\Exception $e) {
            db::rollback();
            apifasong(['zt' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * @name 求购列表
     * @author zay
     * @Date 2020/3/21 0021 13:10
     */
    public function buylist($appdata, $userinfo, $type = 1)
    {
        $page = empty($appdata['page']) ? 1 : $appdata['page'];
        $phone = !empty($appdata['phone']) ? $appdata['phone'] : '';
        $limit = 20;
        $desc = 'desc';
        $list = DB('ppdd')->alias('p')
            ->field('p.id,p.num,p.sell_num,p.price,p.total_money,p.zt,p_user,u.headimg,p.time,p_id')
            ->join('user u', 'u.id=p.p_id', 'left');
        if ($type == 1) {
            if($page>10){
                apifasong(['zt' => 0, 'msg' => '只能获取200单']);
            }
            $desc = 'asc';
            $list->where(['p.zt' => 0]);
            if ($phone) {
                $list->where(['p.p_user' => $phone]);
            }
        } else {
            $list->where(['p.p_id' => $userinfo['id']]);
        }
        $list = $list->where(['p.is_del' => 0])
            ->order('p.time', $desc)
            ->limit($limit, ($page - 1) * $limit)
            ->select();
        //求购大厅手机号码进行处理
        if($type == 1){
            foreach($list as $k=>&$v){
                $v['p_user'] = authcodenum($v['id'], 'encode');
            }
        }
        apifasong(['zt' => 1, 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * @name 买家已付款
     * @author zay
     * @Date 2020/3/21 0021 13:52
     */
    public function pay($appdata, $userinfo)
    {
        DB::startTrans();
        try {
            $order_id = $appdata['order_id'];
            if (empty($order_id)) {
                throw new \Exception('缺少必要的参数');
            }
            $order = DB('ppdd_jiaoyi')->where(['id' => $order_id, 'zt' => 1])->find();
            if (empty($order)) {
                throw new \Exception('订单不是待付款状态');
            }
            if ($order['buy_id'] != $userinfo['id']) {
                throw new \Exception('不是买家不能付款');
            }
            $res = DB('ppdd_jiaoyi')->where(['id' => $order_id])->update(['zt' => 4, 'update_time' => time()]);
            if (!$res) {
                throw new \Exception('操作失败');
            }
            Db::commit();
            //付款成功给卖家发短信
            $retsms = sendsms($order['sell_user'], 'jywc',2);
            apifasong(['zt' => 1, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            Db::rollback();
            apifasong(['zt' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * @name 卖家放币
     * @author zay
     * @Date 2020/3/21 0021 13:52
     */
    public function confirm($appdata, $userinfo)
    {
        Db::startTrans();
        try {
            $order_id = $appdata['order_id'];
            if (empty($order_id)) {
                throw new \Exception('缺少必要的参数');
            }
            $order = DB('ppdd_jiaoyi')->where(['id' => $order_id])->find();
            if (empty($order)) {
                throw new \Exception('订单不存在');
            }
            if (!in_array($order['zt'], [4, 5])) {
                throw new \Exception('不能放币');
            }
            if ($order['sell_id'] != $userinfo['id']) {
                throw new \Exception('不是卖家不能放币');
            }
            $res = DB('ppdd_jiaoyi')->where(['id' => $order_id])->update(['zt' => 2, 'update_time' => time(), 'confirm_time' => time()]);
            if (!$res) {
                throw new \Exception('操作失败');
            }
            //如果求购单数量买完 求购单完成
            $qiugou_order = DB('ppdd')->where(['id' => $order['p_order_id'], 'is_del' => 0])->find();
            if ($qiugou_order && $qiugou_order['num'] == $qiugou_order['sell_num']) {
                $res = DB('ppdd')->where(['id' => $order['p_order_id'], 'is_del' => 0])->update(['zt' => 2, 'update_time' => time()]);
                if (!$res) {
                    throw new \Exception('求购单状态更新失败');
                }
            }
            //如果有投诉记录 把投诉记录处理掉
            $tousu_info = Db('tousu')->whereIn('zt', [0, 2])->where(['pid' => $order_id])->find();
            if (!empty($tousu_info)) {
                $res = Db('tousu')->where(['id' => $tousu_info['id']])->update(['is_del' => 1, 'deal_time' => time()]);
                if (!$res) {
                    throw new \Exception('投诉记录更新失败');
                }
            }
            //添加用户币使用记录
            //卖家币减少 买家币增加
            $insert_log[] = [
                'uid' => $order['sell_id'],
                'uname' => $order['sell_user'],
                'type' => 2,
                'mqian' => $userinfo['idc'],
                'money' => -($order['num'] + $order['fee']),
                'mhou' => $userinfo['idc'] - $order['num'] - $order['fee'],
                'note' => '卖家出售成功',
                'oid' => $order['buy_id'],
                'order_id' => $order['id'],
                'order_sn' => $order['g_order_sn'],
                'oname' => $order['buy_user'],
                'time' => time(),
            ];
            //买家币使用记录
            //获取买家账户余额
            $buy_userinfo = userinfobyuname($order['buy_user']);
            $insert_log[] = [
                'uid' => $order['buy_id'],
                'uname' => $order['buy_user'],
                'type' => 1,
                'mqian' => $buy_userinfo['idc'],
                'money' => $order['num'],
                'mhou' => $buy_userinfo['idc'] + $order['num'],
                'note' => '买家购买成功',
                'oid' => $order['sell_id'],
                'order_id' => $order['id'],
                'order_sn' => $order['g_order_sn'],
                'oname' => $order['sell_user'],
                'time' => time(),
            ];
            $res = DB('logocoin')->insertAll($insert_log);
            if (!$res) {
                throw new \Exception('币使用记录添加失败');
            }
            //更新账户余额
            $res = Db('user')->where(['id' => $order['buy_id']])->update(['idc' => $buy_userinfo['idc'] + $order['num'], 'update_time' => time()]);
            $res1 = Db('user')->where(['id' => $order['sell_id']])->update([
                'idc' => $userinfo['idc'] - $order['num'] - $order['fee'],
                'idc_freeze' => $userinfo['idc_freeze'] - $order['num'] - $order['fee'],
                'update_time' => time()
            ]);
            if (!$res || !$res1) {
                throw new \Exception('账户更新失败');
            }
            Db::commit();
            apifasong(['zt' => 1, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            Db::rollback();
            apifasong(['zt' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * @name 取消交易
     * @author zay
     * @Date 2020/3/25 0025 09:30
     */

    public function cancel($appdata, $userinfo)
    {
        DB::startTrans();
        try {
            $order_id = $appdata['order_id'];
            if (empty($order_id)) {
                throw new \Exception('缺少必要的参数');
            }
            $order = Db('ppdd_jiaoyi')->where(['id' => $order_id])->find();
            if (empty($order)) {
                throw new \Exception('订单不存在');
            }
            if ($order['buy_id'] != $userinfo['id']) {
                throw new \Exception('不是买家，不可以取消');
            }
            if ($order['zt'] != 1) {
                throw new \Exception('订单无法取消');
            }
            //交易取消：修改交易状态，返还求购单已出售数量,解除卖家已冻结数量
            $res = Db('ppdd_jiaoyi')->where(['id' => $order_id])->update(['zt' => 3, 'update_time' => time()]);
            if (!$res) {
                throw new \Exception('状态修改失败');
            }
            $res = DB('ppdd')->where(['id' => $order['p_order_id']])->setDec('sell_num', $order['num']);
            if (!$res) {
                throw new \Exception('求购数据修改失败');
            }
            //减少卖家冻结
            $res = DB('user')->where(['id' => $order['sell_id']])->setDec('idc_freeze', ($order['num'] + $order['fee']));
            if (!$res) {
                throw new \Exception('卖家冻结数量修改失败');
            }
            Db::commit();
            apifasong(['zt' => 1, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            DB::rollback();
            apifasong(['zt' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * @name 投诉
     * @author zay
     * @Date 2020/3/21 0021 16:17
     */

    public function tousu($appdata, $userinfo)
    {
        DB::startTrans();
        try {
            $order_id = $appdata['order_id'];
            $text = $appdata['text'];
            $image = isset($appdata['image']) ? $appdata['image'] : '';
            if (empty($order_id)) {
                throw new \Exception('缺少必要的参数');
            }
            $order = DB('ppdd_jiaoyi')->where(['id' => $order_id])->find();
            if (empty($order)) {
                throw new \Exception('订单不存在');
            }
            if (!in_array($order['zt'], [4, 5])) { //KM++
                throw new \Exception('该订单不能投诉');
            }
            //查询投诉记录
            $tousu_info = DB('tousu')->where(['pid' => $order_id])->find();
            //获取系统超时时间
            if (empty($tousu_info)) {
                if ($order['sell_id'] != $userinfo['id']) {
                    throw new \Exception('此订单暂时不能投诉');
                }
            }
            $res = DB('ppdd_jiaoyi')->where(['id' => $order_id])->update(['zt' => 5, 'update_time' => time()]);
            if (!$res) {
                throw new \Exception('操作失败');
            }
            $buser = $order['sell_user'];
            if ($userinfo['id'] != $order['buy_id']) {
                $buser = $order['buy_user'];
            }
            //如果记录不存在是投诉 存在是申诉
            if (empty($tousu_info)) {
                //添加投诉记录
                $insert_data = [
                    'uid' => $userinfo['id'],
                    'user' => $userinfo['uname'],
                    'buser' => $buser,
                    'text' => $text,
                    'pid' => $order['id'],
                    'create_time' => time(),
                    'image' => $image,
                ];
                $res = DB('tousu')->insert($insert_data);
                if (!$res) {
                    throw new \Exception('投诉失败');
                }
            } else {
                if (in_array($tousu_info['zt'], [1, 3])) {
                    throw new \Exception('投诉已处理，不能申诉');
                }
                if ($tousu_info['zt'] == 2) {
                    throw new \Exception('请勿重复申诉');
                }
                //添加申诉
                $update_data = [
                    'zt' => 2,
                    'btext' => $text,
                    'btime' => time(),
                    'bimage' => $image,
                ];
                $res = DB('tousu')->where(['id' => $tousu_info['id']])->update($update_data);
                if (!$res) {
                    throw new \Exception('申诉失败');
                }
            }
            Db::commit();
            apifasong(['zt' => 1, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            Db::rollback();
            apifasong(['zt' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * @name 申诉
     * @author zay
     * @Date 2020/3/21 0021 16:17
     */

    public function appeal($appdata, $userinfo)
    {
        DB::startTrans();
        try {
            $order_id = $appdata['order_id'];
            $text = $appdata['text'];
            $image = isset($appdata['image']) ? $appdata['image'] : '';
            if (empty($order_id)) {
                throw new \Exception('缺少必要的参数');
            }
            $order = DB('ppdd_jiaoyi')->where(['id' => $order_id])->find();
            if (empty($order)) {
                throw new \Exception('订单不存在');
            }
            //查询投诉记录
            $tousu_info = DB('tousu')->where(['pid' => $order_id['id']])->find();
            if (empty($tousu_info) || $tousu_info['zt'] == 1) {
                throw new \Exception('投诉已处理，不能申诉');
            }
            //添加投诉记录
            $update_data = [
                'btext' => $text,
                'btime' => time(),
                'bimage' => $image,
            ];
            $res = DB('tousu')->where(['id' => $tousu_info['id']])->update($update_data);
            if (!$res) {
                throw new \Exception('申诉失败');
            }
            Db::commit();
            apifasong(['zt' => 1, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            Db::rollback();
            apifasong(['zt' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * @name 交易详情
     * @author zay
     * @Date 2020/3/21 0021 17:59
     */

    public function detail($appdata, $userinfo)
    {
        try {
            $order_id = $appdata['order_id'];
            if (empty($order_id)) {
                throw new \Exception('缺少必要的参数');
            }
            $order = Db('ppdd_jiaoyi')
                ->field('id,num,price,total_money,zt,time,g_order_sn,buy_id,sell_id,buy_user,sell_user,update_time,fee')
                ->where(['id' => $order_id])->find();
            if (empty($order)) {
                throw new \Exception('订单不存在');
            }
            //获取买家和卖家真实姓名
            $sell_userinfo = userinfobyid($order['sell_id']);
            $buy_userinfo = userinfobyid($order['buy_id']);
            $order['sell_truename'] = !empty($sell_userinfo['truename']) ? $sell_userinfo['truename'] : '';
            $order['buy_truename'] = !empty($buy_userinfo['truename']) ? $buy_userinfo['truename'] : '';
            $order['time'] = date('Y-m-d H:i:s', $order['time']);
            $order['current_time'] = time();
            $setting = setting();
            $expire_time = 24 * 60;
            if ($order['zt'] == 1) {
                $expire_time = $setting['repay_cancel'];
            } elseif ($order['zt'] == 4) {
                $expire_time = $setting['send_coin'];
            }
            //添加投诉用户id
            $tousu_info = DB('tousu')->where(['pid' => $order['id']])->find();
            $tousu_uname = '';
            if ($tousu_info) {
                $tousu_uname = $tousu_info['user'];
            }
            $order['tousu_uname'] = $tousu_uname;
            $order['tousu_info'] = [
                'text' => $tousu_info['text'],
                'image' => $tousu_info['image'],
                'zt' => $tousu_info['zt'],
            ];
            if ($order['sell_id'] == $userinfo['id']) {
                $other_id = $order['buy_id'];
            } else {
                $other_id = $order['sell_id'];
            }
            //获取用户微信号、支付宝
            $pay_info = Db('bank')->where(['uid' => $order['sell_id']])->whereIn('type', [1, 2, 3])->column('type,account_num,code,bank', 'type');
            $wechat = Db('bank')->field('account_num')->where(['uid' => $other_id, 'type' => 2])->find();
            $order['wechat'] = isset($wechat['account_num']) ? $wechat['account_num'] : '';
            $order['pay_code'] = isset($pay_info[1]['code']) ? $pay_info[1]['code'] : '';
            $order['bank_num'] = isset($pay_info[3]['account_num']) ? $pay_info[3]['account_num'] : '';
            $order['bank_branch'] = isset($pay_info[3]['bank']) ? $pay_info[3]['bank'] : '';
            $order['end_time'] = $order['update_time'] + $expire_time * 60;
            $order['is_tousu'] = 0;
            if ($order['zt'] == 4 && $order['end_time'] < time()) {
                $order['is_tousu'] = 1;
            }
            apifasong(['zt' => 1, 'msg' => '获取成功', 'data' => $order]);
        } catch (\Exception $e) {
            apifasong(['zt' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * @name 取消委托
     * @author zay
     * @Date 2020/3/23 0023 09:54
     */

    public function trustcancel($appdata, $userinfo)
    {
        try {
            $order_id = $appdata['order_id'];
            if (empty($order_id)) {
                throw new \Exception('缺少必要的参数');
            }
            //获取委托信息
            $order = DB('ppdd')->where(['id' => $order_id, 'is_del' => 0, 'p_id' => $userinfo['id']])->find();
            if (empty($order)) {
                throw new \Exception('订单不存在');
            }
            if ($order['zt'] != 0) {
                throw new \Exception('订单不是待撤销状态');
            }
            $jiaoyi_undo_time = setting('jiaoyi_undo_time');
            if ($order['time'] + $jiaoyi_undo_time * 60 > time()) {
                throw new \Exception('挂单' . $jiaoyi_undo_time . '分钟之内不能取消');
            }
            $res = DB('ppdd')->where(['id' => $order_id])->update(['zt' => 3, 'cancel_time' => time(), 'update_time' => time()]);
            if (!$res) {
                throw new \Exception('操作失败');
            }
            apifasong(['zt' => 1, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            apifasong(['zt' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * @name 交易记录
     * @author zay
     * @Date 2020/3/23 0023 11:49
     */
    public function jiaoyilist($appdata, $userinfo)
    {
        $page = empty($appdata['page']) ? 1 : $appdata['page'];
        $limit = 20;
        $list = DB('ppdd_jiaoyi')
            ->field('id,num,time,zt,sell_id,sell_user,buy_id,buy_user')
            ->where(['sell_id' => $userinfo['id']])
            ->whereOr(['buy_id' => $userinfo['id']])
            ->order('time desc')
            ->limit($limit, ($page - 1) * $limit)
            ->select();
        apifasong(['zt' => 1, 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * @name 日K线
     * @author zay
     * @Date 2020/3/23 0023 16:01
     */

    public function kday($appdata, $userinfo)
    {
        //
        $start_time = strtotime('-15 day');
        $list = Db('k_day')
            ->field('max_price,min_price,num,open_price,stop_price,date,update_time')
            ->where('update_time', '>=', $start_time)->order('update_time asc')->select();
        $getrixian = [];
        foreach ($list as $value) {
            $getrixian[] = [
                date('Y/m/d', $value['update_time']),
                $value['open_price'], $value['stop_price'], $value['min_price'], $value['max_price']    //今开，今收，最低，最高
            ];
        }
        apifasong(['zt' => 1, 'msg' => '获取成功', 'data' => $getrixian]);
    }

    /**
     * @name 小时k线
     * @author zay
     * @Date 2020/3/23 0023 16:44
     */

    public function khours($appdata, $userinfo)
    {
        $list = DB("k_hours")->field('time,price')->whereTime('time', 'today')->order('time asc')->select();
        $getshifen = [];
        foreach ($list as $value) {
            $H = date('H:00', $value['time']);
            $getshifen[$H] = [
                $H,
                $value['price']
            ];
        }
        apifasong(['zt' => 1, 'msg' => '获取成功', 'data' => array_values($getshifen)]);
    }

    /**
     * @name 获取涨幅
     * @author zay
     * @Date 2020/3/25 0025 13:27
     */

    public function increase($appdata, $userinfo)
    {
        $list = Db('k_day')
            ->field('max_price,min_price,num')
            ->order('update_time asc')->limit(1)->find();
        if (empty($list)) {
            $list['max_price'] = setting('current_price');
            $list['min_price'] = setting('current_price');
            $list['num'] = 0;
        }
        //计算涨幅
        $fu = ($list['max_price'] / $list['min_price'] - 1) * 100;
        $list['fu'] = number_format($fu, 2);
        //获取最后成交价格
        $zuihou_jiaoyi = DB('ppdd_jiaoyi')->field('price')->order('time desc')->limit(1)->find();
        $list['zuihou'] = $zuihou_jiaoyi ? $zuihou_jiaoyi['price'] : setting('current_price');
        $list['current_price'] = setting('current_price');
        apifasong(['zt' => 1, 'msg' => '', 'data' => $list]);
    }

    /**
     * @name 投诉信息
     * @author zay
     * @Date 2020/4/13 0013 14:20
     * @param $appdata
     * @param $userinfo
     */

    public function tousu_info($appdata, $userinfo)
    {
        try {
            if (empty($appdata['order_id'])) {
                throw new \Exception('缺少必要参数');
            }
            $order_id = $appdata['order_id'];
            $uname = $userinfo['uname'];
            $info = Db('tousu')->where(['pid' => $order_id, 'is_del' => 0])->where(function ($query) use ($uname) {
                $query->where(['user' => $uname])
                    ->whereOr(['buser' => $uname]);
            })->find();
            apifasong(['zt' => 1, 'msg' => '获取成功', 'data' => $info]);
        } catch (\Exception $e) {
            apifasong(['zt' => 0, 'msg' => $e->getMessage()]);
        }
    }
}